package br.com.petrobrasrj.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

@Stateless
public class GenericDao<T> implements IGenericDao<T> {

	private static final long serialVersionUID = 8913854433547892847L;

	@PersistenceContext(name = "petrobras", unitName = "petrobras")
	public EntityManager em;

	protected EntityManager getEntityManager() {
		if (em == null) {
			throw new IllegalStateException("entityManger e Nulo ou Invalido");
		}
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	

	// ********************************CRUD************************************

	public void delete(T objeto)  {
		em.remove(em.merge(objeto));
	}

	public T insert(T objeto) {
		em.persist(objeto);
		return objeto;
	}

	public T update(T t) {
		em.merge(t);
		return t;
	}
	
	public T findById(Class<T> modelClass, Object id) {
		T t = em.find(modelClass, id);
		return t;
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll(Class<T> modelClass) {
		if (modelClass == null) {
			throw new IllegalArgumentException("class nao pode ser null!");
		}

		Criteria criteria = getCriteria(modelClass);
		criteria.addOrder(Order.asc("id"));

		List<T> lista = criteria.list();

		return lista;
	}
	
	protected Criteria getCriteria(Class<T> modelClass) {
		return montarCriteria(modelClass);
	}

	private Criteria montarCriteria(Class<T> modelClass) {
		Session session = em.unwrap(Session.class);

		String aliasEntityRoot = modelClass.getClass().getSimpleName().substring(0, 1).toLowerCase() + modelClass.getSimpleName().substring(1, modelClass.getSimpleName().length());

		Criteria criteria = session.createCriteria(modelClass.getName(), aliasEntityRoot);
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return criteria;
	}
}
